import psutil
import requests
import json


def get_chrome_processes():
    chrome_processes = []
    for proc in psutil.process_iter(['pid', 'name']):
        if 'chrome' in proc.info['name'].lower():
            chrome_processes.append(proc)
    return chrome_processes


def get_chrome_tabs(remote_debugging_port=9222):
    try:
        response = requests.get(f'http://localhost:{remote_debugging_port}/json')
        tabs = json.loads(response.text)
        return tabs
    except Exception as e:
        print(f"Error connecting to Chrome remote debugging: {e}")
        return []


def is_page_open(url, remote_debugging_port=9222):
    tabs = get_chrome_tabs(remote_debugging_port)
    for tab in tabs:
        if 'url' in tab and url in tab['url']:
            return True
    return False


if __name__ == "__main__":

    url_to_check = "https://plm-test.digithings.cn/cart/list"

    chrome_processes = get_chrome_processes()
    if not chrome_processes:
        print("Google Chrome is not running.")
    else:
        if is_page_open(url_to_check):
            print(f"The page {url_to_check} 在 Google Chrome 中打开")
        else:
            print(f"The page {url_to_check} 不在 Google Chrome 中打开")
